// API请求工具
import { refreshToken as refreshTokenApi } from '@/api/user.js';

const BASE_URL = 'http://192.168.110.1:80/api';

// 是否正在刷新Token
let isRefreshing = false;
// 请求队列
let requestQueue = [];

// 请求拦截器
const requestInterceptor = (config) => {
  // 获取token
  const token = uni.getStorageSync('token');
  if (token) {
    config.header = {
      ...config.header,
      'Authorization': `Bearer ${token}`
    };
  }
  return config;
};

// 响应拦截器
const responseInterceptor = (response) => {
  const { statusCode, data } = response;
  
  // HTTP状态码处理
  if (statusCode !== 200) {
    // 401未授权
    if (statusCode === 401) {
      return handleTokenError(response);
    }
    // 其他HTTP错误
    uni.showToast({
      title: '服务器异常，请稍后重试',
      icon: 'none'
    });
    return Promise.reject(new Error(`HTTP错误: ${statusCode}`));
  }
  
  // 业务状态码处理
  if (data.code !== 200 && data.code !== 201) {
    // 401未登录或token过期
    if (data.code === 401) {
      return handleTokenError(response);
    }
    
    // 其他业务错误
    uni.showToast({
      title: data.message || '请求失败',
      icon: 'none'
    });
    return Promise.reject(data);
  }
  
  // 请求成功
  return data;
};

// 处理Token错误
const handleTokenError = (response) => {
  console.log('Token验证失败', response);
  const token = uni.getStorageSync('token');
  const refreshTokenStr = uni.getStorageSync('refreshToken');
  
  // 如果没有刷新令牌，直接登出
  if (!refreshTokenStr) {
    console.log('没有刷新令牌，执行登出');
    handleUnauthorized();
    return Promise.reject(new Error('登录已过期，请重新登录'));
  }
  
  // 如果正在刷新Token，则将请求加入队列
  if (isRefreshing) {
    console.log('正在刷新Token，请求加入队列');
    return new Promise((resolve, reject) => {
      requestQueue.push(() => {
        resolve(request(response.config));
      });
    });
  }
  
  // 开始刷新Token
  isRefreshing = true;
  console.log('开始刷新Token');
  
  // 调用刷新Token接口
  return refreshTokenApi(refreshTokenStr)
    .then(res => {
      console.log('刷新Token成功', res);
      // 更新Token
      const { token, refreshToken: newRefreshToken } = res.data;
      uni.setStorageSync('token', token);
      if (newRefreshToken) {
        uni.setStorageSync('refreshToken', newRefreshToken);
      }
      
      // 执行队列中的请求
      console.log('执行队列中的请求', requestQueue.length);
      requestQueue.forEach(callback => callback());
      requestQueue = [];
      
      // 重新发起当前请求
      const config = response.config || { url: response.request.url, method: response.request.method, data: response.request.data };
      return request(config);
    })
    .catch(error => {
      console.error('刷新Token失败', error);
      // 刷新Token失败，清空登录状态
      handleUnauthorized();
      return Promise.reject(error);
    })
    .finally(() => {
      isRefreshing = false;
    });
};

// 处理未授权情况
const handleUnauthorized = () => {
  console.log('执行未授权处理');
  // 清除登录信息
  uni.removeStorageSync('token');
  uni.removeStorageSync('refreshToken');
  uni.removeStorageSync('userInfo');
  
  // 如果不在登录页，则显示提示并跳转
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const currentRoute = currentPage ? currentPage.route : '';
  console.log('当前页面路径', currentRoute);
  
  if (currentRoute !== 'pages/login/login') {
    uni.showToast({
      title: '登录已过期，请重新登录',
      icon: 'none'
    });
    
    // 跳转登录页
    setTimeout(() => {
      uni.navigateTo({
        url: '/pages/login/login'
      });
    }, 1500);
  }
};

// 请求方法
const request = (options) => {
  // 处理请求配置
  const config = requestInterceptor({
    url: options.url.indexOf('http') === 0 ? options.url : BASE_URL + options.url,
    method: options.method || 'GET',
    data: options.data || options.params,
    header: options.header || {}
  });
  
  // 发起请求
  return new Promise((resolve, reject) => {
    uni.request({
      ...config,
      success: (res) => {
        try {
          const result = responseInterceptor(res);
          resolve(result);
        } catch (error) {
          reject(error);
        }
      },
      fail: (err) => {
        console.error('网络请求失败', err);
        uni.showToast({
          title: '网络连接异常，请检查网络设置',
          icon: 'none'
        });
        reject(err);
      }
    });
  });
};

// 导出各种请求方法
export const get = (url, params = {}) => {
  return request({
    url,
    method: 'GET',
    params
  });
};

export const post = (url, data = {}) => {
  return request({
    url,
    method: 'POST',
    data
  });
};

export const put = (url, data = {}) => {
  return request({
    url,
    method: 'PUT',
    data
  });
};

export const del = (url, data = {}) => {
  return request({
    url,
    method: 'DELETE',
    data
  });
};

export default request; 
export { BASE_URL };